// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// z [author] rhyme_lph
// M [email]  rhymelph@gmail.com
// h [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/services_entity.dart';
import 'package:finance_app/src/provider/dashboard/products_services/products_and_services_provider.dart';
import 'package:finance_app/src/provider/dashboard/products_services/views/services_provider.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/button/filter_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/chip/normal_chip.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/select/service_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ServicesView extends StatefulWidget {
  final bool isSelectMode;
  final String initStatus;

  const ServicesView({Key key, this.isSelectMode, this.initStatus})
      : super(key: key);

  @override
  _ServicesViewState createState() => _ServicesViewState();
}

class _ServicesViewState extends State<ServicesView>
    with
        StatefulPresenter<ServicesView, ProductsAndServicesProvider,
            ServicesProvider>,
        KeepAliveMixin {
  @override
  void initState() {
    if (widget.initStatus != null) {
      provider.currentSelectActive = widget.initStatus;
    }
    provider.isSelectMode = widget.isSelectMode;
    super.initState();
  }

  @override
  Widget buildEmptyWidget(BaseProvider _, BuildContext context) {
    return ColoredBox(
      color: Colors.white,
      child: Column(
        children: [
          _buildTopWidget(),
          Expanded(
            child: super.buildEmptyWidget(provider, context),
          ),
        ],
      ),
    );
  }

  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            _buildTopWidget(),
            Expanded(
              child: listBuilder<Map<String, List<ServicesEntity>>>(
                selector: (_, __) =>
                    Map<String, List<ServicesEntity>>.from(__.groupMap),
                builder: (BuildContext context,
                        Map<String, List<ServicesEntity>> value,
                        Widget child) =>
                    SmartRefresher(
                  controller: provider.refreshController,
                  onRefresh: provider.onRefresh,
                  onLoading: provider.onLoadMore,
                  enablePullUp: false,
                  child: value.entries.length == 0
                      ? super.buildEmptyWidget(provider, context)
                      : CustomScrollView(
                          controller: provider.controller,
                          slivers: buildSearchWidget(),
                        ),
                ),
              ),
            ),
          ],
        ),
      );

  Widget buildTimeSoreAndFilter() {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: getDp(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _buildTimeSelect(),
          FilterButton(
            onPressed: provider.onShowServiceFilter,
          ),
        ],
      ),
    );
  }

  Widget _buildFilterList() {
    return listBuilder<int>(
        builder: (BuildContext context, int value, Widget child) => value == 0
            ? Container()
            : Container(
                height: getDp(30),
                margin: EdgeInsets.only(
                  bottom: getDp(15),
                ),
                alignment: Alignment.centerLeft,
                child: ListView.separated(
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(10),
                  ),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) =>
                      _buildFilterItem(context, index),
                  itemCount: value,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      width: getDp(15),
                    );
                  },
                ),
              ),
        selector: (_, __) => __.currentSelectFilterList.length);
  }

  Widget _buildTimeSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: LanguageUtils.translateStatus(value),
              onTap: provider.onSelectActive,
            ),
        selector: (_, __) => __.currentSelectActive);
  }

  Widget _buildFilterItem(BuildContext context, int index) {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalChip(
              title: LanguageUtils.translateFilter(value),
              onClose: () => provider.onRemoveFilter(value),
            ),
        selector: (_, __) => __.currentSelectFilterList[index]);
  }

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<ServicesEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<ServicesEntity> data, int i) {
    return listBuilder<ServicesEntity>(
        selector: (_, __) => __.currentSelectContact,
        builder: (BuildContext context, ServicesEntity value, Widget child) =>
            PressedOpacityButton(
              onPressed: () => provider.onSelectServices(data[i]),
              padding: EdgeInsets.symmetric(
                horizontal: getDp(29),
                vertical: getDp(21),
              ),
              border: data.length == i + 1
                  ? null
                  : Border(
                      bottom:
                          BorderSide(color: aceGrayColor, width: getDp(0.5))),
              color: value == data[i] ? aceSelectBackgroundColor : Colors.white,
              child: ServiceRadio(
                isSelect: value?.id == data[i]?.id,
                title: data[i].name,
                isSelectMode: widget.isSelectMode,
                isActivated: data[i].isActivated == 1,
                sellBuy:
                    '${data[i].currencyCode} ${data[i].enableSell == 0 ? '-' : CashUtils.formatCashAmount(data[i].price)} / ${data[i].enablePurchase == 0 ? '-' : CashUtils.formatCashAmount(data[i].purchasePrice)}',
              ),
            ));
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }

  Widget _buildTopWidget() {
    return Column(
      children: [
        AppSpaces.h20,
        SearchInputField(
          controller: provider.searchController,
          focusNode: provider.searchFocusNode,
        ),
        if (widget.isSelectMode == true)
          listBuilder<bool>(
            selector: (_, __) =>
                __.searchController.text.length > 0 && __.groupMap.isEmpty,
            builder: (BuildContext context, bool value, Widget child) =>
                Config.hasPermission(PermissionUtils.productService)
                    ? NormalFormWrapper(
                        child: value == true
                            ? AddButton(
                                title:
                                    '${S.current.add} "${provider.searchController.text}"',
                                onTap: () => provider.onShowAddServicesName(
                                    provider.searchController.text),
                              )
                            : AddButton(
                                title: S.current.add_service,
                                onTap: provider.onShowAddServices,
                              ),
                      )
                    : AppSpaces.h20,
          )
        else
          listBuilder<bool>(
            selector: (_, __) =>
                __.searchController.text.length > 0 && __.groupMap.isEmpty,
            builder: (BuildContext context, bool value, Widget child) =>
                value == true
                    ? Config.hasPermission(PermissionUtils.productService)
                        ? NormalFormWrapper(
                            child: AddButton(
                              title:
                                  '${S.current.add} "${provider.searchController.text}"',
                              onTap: () => provider.onShowAddServicesName(
                                  provider.searchController.text),
                            ),
                          )
                        : AppSpaces.h20
                    : buildTimeSoreAndFilter(),
          ),
        _buildFilterList(),
      ],
    );
  }
}
